package cn.eng.order.service.impl;

import cn.eng.basic.util.AjaxResult;
import cn.eng.basic.util.CodeGenerateUtils;
import cn.eng.basic.util.LoginContext;
import cn.eng.order.domain.OrderPetAcquisition;
import cn.eng.order.domain.OrderProduct;
import cn.eng.order.mapper.OrderProductMapper;
import cn.eng.order.service.IOrderProductService;
import cn.eng.basic.service.impl.BaseServiceImpl;
import cn.eng.pet.dto.OrderDto;
import cn.eng.product.domain.Product;
import cn.eng.user.domain.Logininfo;
import cn.eng.user.domain.User;
import cn.eng.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class OrderProductServiceImpl extends BaseServiceImpl<OrderProduct> implements IOrderProductService {
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        OrderProduct orderProduct = orderProductMapper.loadById(id);
        orderProduct.setState(-1);
        orderProductMapper.update(orderProduct);
    }

    /**
     * 确认订单
     * @param orderDto
     */
    @Override
    public void confirm(OrderDto orderDto) {

    }

    /**
     * 下单
     * @param product
     * @return
     */
    @Override
    public AjaxResult adopt(Product product, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
       User user=  userMapper.loadByLogininfoId(logininfo.getId());
        OrderProduct order = product2Order(product,user);
        orderProductMapper.save(order);
        return new AjaxResult(true,"下单成功,请在24小时内完成支付");
    }

    private OrderProduct product2Order(Product product, User user) {
        OrderProduct ord = new OrderProduct();
        ord.setDigest("[服务订单]购买1次"+product.getName());
        String orderSn = CodeGenerateUtils.generateOrderSn(product.getId());
        ord.setState(0);
        ord.setOrderSn(orderSn);
        ord.setPrice(product.getSaleprice());
        String paySn =  CodeGenerateUtils.generateUnionPaySn();
        ord.setPaySn(paySn);
        ord.setLastPayTime(new Date());
        ord.setUserId(user.getId());
        return ord;
    }
}
